
/**
 * ajax请求封装
 * @param {Object} options 
    
 */
function request(options){
    let defaults = {
        baseUrl:'http://120.76.247.5:2003/api',
        method:'get',
        async:true,
        header:{},
        // data:{}
    }
    const opt = Object.assign({},defaults,options)

    // 处理发送的数据：opt.data
    let params = ''
    if(opt.data){
        // {a:10,b:20,c:30} -> a=10&b=20&c=30
        const arr = [];// ['a=10','b=20','c=30']
        for(let k in opt.data){
            arr.push(`${k}=${opt.data[k]}`)
        }
        params = arr.join('&')

        // get请求，参数写入url
        if(opt.method == 'get'){
            opt.url = opt.url + '?' + params
            params = null;
        }
    }

    let xhr = new XMLHttpRequest();

    // 处理返回数据
    xhr.onload = function(){
        const data = JSON.parse(xhr.responseText)
        if(typeof opt.success==='function'){
            opt.success(data)
        }
    }

    xhr.open(opt.method,opt.url,opt.async)

    if(opt.method === 'post'){
        xhr.setRequestHeader(
            'Content-Type',
            opt.header['Content-Type'] || 'application/x-www-form-urlencoded'
        )
    }

    xhr.send(params)
}
